import { View } from "@tarojs/components";


import React, { Suspense, useEffect, useRef, useState } from "react";
import Taro from "@tarojs/taro";


import FullBar from "@/components/fullBar";
import useInitAction from "@/hooks/useInitAction";
import { arraysAreEqual, handleInitStoreBaseInfo, showToast, subscribeMessage, toPage } from "@/common/util";
import { EAXMINE_NOTICE_ID, PAGE_TYPE, STORE_KEY, TOPIC_NUM } from "@/common/config";
import {  IUserProfileEditPromise, USER_PROFILE_STATUS } from "@/typing";


import useProfileInfoAction from "@/hooks/useProfileInfoAction";

const DraggableContainer = React.lazy(() => import('../../components/draggableContainer/draggableContainer'));



const TopicSetting: React.FC = () => {
    const { handleShopUserprofileEdit } = useProfileInfoAction()

    // 创建一个ref，用于获取DraggableContainer的DOM元素
    const DraggableContainerRef = useRef<HTMLDivElement>(null)
    // 创建一个state，用于存储话题列表
    const [topicList, setTopicList] = useState<any>([{
        sort: 1,
        title: '',
        id: 0

    }])
  
    const [userStatus, setUserStatus] = useState<USER_PROFILE_STATUS>(USER_PROFILE_STATUS.unknown);
    const [oldTopicList, setOldTopicList] = useState([])
    // 获取初始化动作的参数
    const { placeHolderHeight, bottomSafeHeight } = useInitAction();


    // 创建一个state，用于控制是否显示话题
    const [showTopic, setShowTopic] = useState(false)


    // 处理添加话题
    const handleAddTopic = () => {
        // 如果话题数量已经达到10个，则提示用户
        if (topicList.length === 10) {
            showToast('最多只能添加10个话题')


            return
        }

        // 获取当前话题列表
        const topicTemp = handleSaveTopicList();

        // 将话题列表保存到本地存储
        Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(topicTemp))
        let storeTopicList = Taro.getStorageSync(STORE_KEY.TOPIC)

        // 将本地存储中的话题列表解析为JSON对象
        storeTopicList = JSON.parse(storeTopicList)

        // 更新话题列表
        setTopicList(storeTopicList)
        // console.log(topicList)
        if (topicList[topicList.length - 1].title === '') {
            showToast('有空项，无法添加新的')
            // return
        }

        // 获取当前话题列表中keyName最大的对象
        const maxKeyNameObject = topicList.reduce((maxObj, currentObj) => {
            return parseInt(currentObj.sort) > parseInt(maxObj.sort) ? currentObj : maxObj;
        });

        // 将新的话题添加到话题列表中
        setTopicList([...storeTopicList, { sort: Number(maxKeyNameObject.sort) + 1, title: '', id: 0 }])

    }
    // 处理删除话题
    const handleDeleteTopic = (index) => {
        // 获取当前话题列表
        console.log(index)
        let storeTopicList = Taro.getStorageSync(STORE_KEY.TOPIC)

        // 将本地存储中的话题列表解析为JSON对象
        storeTopicList = JSON.parse(storeTopicList)
        // 更新话题列表
        // setTopicList(storeTopicList)

        // 如果话题数量大于1，则删除指定话题
        if (storeTopicList.length > 1) {
            // const userProfileStatus = Taro.getStorageSync(STORE_KEY.USER_PROFILE_STATUS)

            const newList = storeTopicList.filter((item, index1) => index !== index1)
            setTopicList(newList)

            // 将更新后的话题列表保存到本地存储
            Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(newList))

            // 更新话题列表

        }

    }
    // 保存话题列表
    const handleSaveTopicList = () => {
        // 创建一个空数组，用于存储话题列表
        const topicTemp = [] as any

        // 获取DraggableContainer的子元素
        console.log(`DraggableContainerRef.current----${DraggableContainerRef.current}`)
        const dragChildren = DraggableContainerRef.current?.childNodes;
        console.log(dragChildren)
        if (dragChildren) {
            if (dragChildren?.length === 1) {
                dragChildren.forEach((pItem, index) => {
                    // console.log((pItem.childNodes[0].childNodes[0]['props'].value))
                    if (pItem.childNodes[0].childNodes[0]['props'].value) {
                        // 如果子元素的值不为空，则将子元素的值和keyName添加到话题列表中
                        // console.log(pItem)
                        const id = pItem.childNodes[0].childNodes[0]['props'].id
                        const topicEl = pItem.childNodes[0]['props'].id

                        const sort = id.split('-')[1];
                        // console.log(topicEl)

                        topicTemp.push({
                            title: pItem.childNodes[0].childNodes[0]['props'].value,
                            sort,
                            id: topicEl
                        })
                    }



                })
            } else {
                dragChildren.forEach((pItem, index) => {
                    // console.log((pItem.childNodes[0].childNodes[0]['props'].value))
                    if (pItem.childNodes[1].childNodes[0]['props'].value) {
                        // 如果子元素的值不为空，则将子元素的值和keyName添加到话题列表中
                        // console.log(pItem)
                        const id = pItem.childNodes[1].childNodes[0]['props'].id
                        const topicEl = pItem.childNodes[1]['props'].id

                        const sort = id.split('-')[1];
                        // console.log(topicEl)

                        topicTemp.push({
                            title: pItem.childNodes[1].childNodes[0]['props'].value,
                            sort,
                            id: topicEl
                        })
                    }



                })
            }
        }




        return topicTemp;
        // 返回话题列表


    }
    const handleNextStep = () => {
        // 处理下一步
        const topicTemp = handleSaveTopicList();
        console.log(topicTemp)
        // 获取当前话题列表
        if (topicTemp.length === 0) {
            Taro.showToast({
                title: '至少添加一个话题',
                icon: 'none'
            })
        } else {

            const isLongIndex = topicTemp.findIndex((item) => item.title.length > TOPIC_NUM)
            if (isLongIndex !== -1) {
                Taro.showToast({
                    title: `话题${isLongIndex + 1}描字数不能超过${TOPIC_NUM}个字`,
                    icon: 'none'
                })
            } else {
                Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(topicTemp))
                toPage(PAGE_TYPE.PHOTO_VIDEO)
            }

            // 将话题列表保存到本地存储
        }
        // 跳转到下一个页面

    }


    const handleGoBackAction = () => {
        const userProfileStatus = Taro.getStorageSync(STORE_KEY.USER_PROFILE_STATUS)
        if (userProfileStatus === USER_PROFILE_STATUS.unknown) {
            const topicTemp = handleSaveTopicList();
            if (topicTemp.length > 0) {
                Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(topicTemp))
                // 获取当前话题列表


            }
            Taro.navigateBack()

        } else {
            Taro.navigateBack()
        }


    }
    const handleSaveTopic = () => {

        const storeTopicList = JSON.parse(Taro.getStorageSync(STORE_KEY.TOPIC) || '[]')
        console.log(storeTopicList)
        if (storeTopicList.length === 0) {
            showToast('至少添加一个话题')
            return

        }

        const storeTopicListId = storeTopicList.map((item: any) => item.id)
        const oldTopicListId = oldTopicList.map((item: any) => item.id)
        console.log(oldTopicList)

        let hasEdit = arraysAreEqual(storeTopicListId, oldTopicListId)
        if (oldTopicList.length === 1 && storeTopicList.length === 1 && storeTopicList[0].id === oldTopicList[0].id) {
            //判断2个字符串内容是否一致
            if (storeTopicList[0].title !== oldTopicList[0].title) {
                hasEdit = true;
            }

        }
        // console.log(hasEdit)
        // return
        if (hasEdit) {
            const storeTopicList = JSON.parse(Taro.getStorageSync(STORE_KEY.TOPIC))
            const computedTopObj = {}

            storeTopicList.forEach((topic, index) => {
                const keyVal = `topic[${[index]}][title]`
                const keyIdVal = `topic[${[index]}][id]`

                // const sortVal = `topic[${[index]}][sort]`
                computedTopObj[keyIdVal] = topic['id']
                computedTopObj[keyVal] = topic['title']
                // computedTopObj[sortVal] = index

            })
            Taro.showModal({
                title: '提示',
                content: '确定修改话题吗？',
                success: async function (res) {
                    if (res.confirm) {
                        Taro.showLoading({
                            title: '修改中',
                            mask: true
                        })
                        try {
                            const editRes = await handleShopUserprofileEdit({ ...computedTopObj }) as IUserProfileEditPromise
                            Taro.hideLoading({

                            })



                            const storeBaseUserInfo = handleInitStoreBaseInfo()
                            storeBaseUserInfo['modify_field']['topic'] = USER_PROFILE_STATUS.disable
                            Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))

                            const { msg } = editRes
                            showToast(msg)
                            subscribeMessage([EAXMINE_NOTICE_ID]).then(() => {
                                
                                Taro.navigateBack();
                            })


                        } catch (error) {
                            Taro.hideLoading({

                            })
                        }


                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        }


    }
    useEffect(() => {
        setShowTopic(false)
        const storeUserStatus = Taro.getStorageSync(STORE_KEY.USER_PROFILE_STATUS) || USER_PROFILE_STATUS.unknown;
        setUserStatus(storeUserStatus)
        let storeTopicList = Taro.getStorageSync(STORE_KEY.TOPIC)
        if (storeTopicList && storeTopicList.length > 0) {
            storeTopicList = JSON.parse(storeTopicList)
            setTopicList(storeTopicList)
            setOldTopicList(storeTopicList)
        } else {
            storeTopicList = [{
                sort: 1,
                title: '',
                id: 0
            }]
        }
        setShowTopic(true)
        return () => {

        };
    }, []);

    return <>
        <View className='min-h-100vh box-border bg-#F6F6F6 ' style={{ paddingBottom: bottomSafeHeight > 0 ? bottomSafeHeight + 'px' : '90rpx' }}>
            <FullBar navName='话题设置' showReturn={true} handleGoBack={handleGoBackAction} />

            {showTopic && <View style={{ paddingTop: placeHolderHeight + 'px' }} className="box-border">
                <View className="px-42px box-border text-#161618 text-30px pt-66px" >用户下单时需要选择一个话题</View>
                <View className="pl-38px pr-34px box-border mt-30px">
                    <Suspense>
                        <DraggableContainer ref={DraggableContainerRef} items={topicList} sort='sort' handleDelete={handleDeleteTopic}></DraggableContainer>
                    </Suspense>

                </View>
                <View className="mt-12px px-50px box-border text-#8232E8 text-28px text-center" onClick={handleAddTopic}>+ 添加话题</View>
                {
                    userStatus === USER_PROFILE_STATUS.enable ? <View onClick={handleSaveTopic} className="w-592px h-92px mx-auto flex items-center justify-center text-#fff text-30px bg-#8232E8 font-medium " style={{ marginTop: topicList.length > 3 ? '100rpx' : '570rpx' }}
                    >保存</View> : <View className=" w-400px h-108px bg-#fff mx-auto flex items-center justify-center text-#333333 text-36px" style={{ marginTop: topicList.length > 3 ? '100rpx' : '570rpx' }} onClick={handleNextStep}>下一步</View>
                }

            </View>}
        </View>
    </>
}
export default TopicSetting;